import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  CreateDateColumn,
  UpdateDateColumn,
  OneToOne,
  JoinColumn,
  DeleteDateColumn,
} from 'typeorm';
import { IsOptional, IsString, MaxLength, IsNumber } from 'class-validator';
import { Type } from 'class-transformer';
import { User } from '@/modules/users/entities/user.entity';
import { ResourceFile } from './resource-file.entity';
import { Song } from './song.entity';
import { CrudValidationGroups } from '@nestjsx/crud';

const { CREATE, UPDATE } = CrudValidationGroups;

@Entity({ name: 'tracks' })
export class Track {
  @IsOptional({ always: true })
  @PrimaryGeneratedColumn()
  id: number;

  @IsOptional({ groups: [UPDATE] })
  @IsString({ always: true })
  @MaxLength(20, { always: true })
  @Column({
    type: 'character varying',
    length: 20,
    comment: '标签',
  })
  tag: string;

  @IsOptional({ always: true })
  @IsNumber()
  @Column({ type: 'real', comment: '时长/秒' })
  duration: number;

  @Type(_type => ResourceFile)
  @OneToOne(_type => ResourceFile)
  @JoinColumn()
  file: ResourceFile;

  @Type(_type => User)
  @ManyToOne(
    _type => User,
    user => user.uploadedTracks,
  )
  uploadedByUser: User;

  @Type(_type => Song)
  @ManyToOne(
    _type => Song,
    song => song.tracks,
  )
  relatedSong: Song;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @DeleteDateColumn()
  deletedAt: Date;
}
